package com.le.tester.javaThink.fifth.chapter24_ConcurrentProgramming;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * createTime：2021/8/18 10:23
 * description：CachedThreadPool3
 */
public class CachedThreadPool3 {
    public static Integer extractResult(Future<Integer> f) {
        try {
            return f.get();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        List<CountingTask> tasks = IntStream.range(0, 10)
                .mapToObj(CountingTask::new)
                .collect(Collectors.toList());

        //只有在所有的任务完成后，invokeAll()才会返回一个Future列表
        List<Future<Integer>> futures = service.invokeAll(tasks);

        Integer sum = futures.stream().map(CachedThreadPool3::extractResult)
                .reduce(0, Integer::sum);

        System.out.println("sum" + sum);
        service.shutdown();


    }
}
